<template>
  <div class="user-manage-page">
    <el-card class="main-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><User /></el-icon>
            <span class="header-title">用户管理</span>
          </div>
          <el-button type="primary" @click="openAddDialog" :icon="Plus">
            新增用户
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名、昵称、邮箱、电话"
          clearable
          style="max-width: 300px;"
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select 
          v-model="filterRole" 
          placeholder="选择角色" 
          clearable
          style="width: 150px;"
          @change="handleSearch"
        >
          <el-option label="全部" value="" />
          <el-option label="普通用户" :value="1" />
          <el-option label="志愿者" :value="2" />
          <el-option label="管理员" :value="3" />
        </el-select>
        <el-button type="primary" @click="handleSearch" :icon="Search">查询</el-button>
        <el-button @click="handleReset" :icon="Refresh">重置</el-button>
      </div>

      <!-- 表格 -->
      <el-table 
        :data="filteredList" 
        border 
        stripe
        v-loading="loading"
        style="width: 100%; margin-top: 20px;"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: '600' }"
      >
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="id" label="用户ID" width="90" align="center">
          <template #default="{ row }">
            <span class="id-text">#{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="avatar" label="头像" width="90" align="center">
          <template #default="{ row }">
            <el-avatar 
              :src="formatImageUrl(row.avatar)" 
              :size="50"
              v-if="row.avatar"
            >
              <el-icon><User /></el-icon>
            </el-avatar>
            <el-avatar :size="50" v-else>
              <el-icon><User /></el-icon>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="140" align="center">
          <template #default="{ row }">
            <span class="username-text">{{ row.username || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="昵称" width="140" align="center">
          <template #default="{ row }">
            <span class="nickname-text">{{ row.nickname || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="email-cell">
              <el-icon><Message /></el-icon>
              <span>{{ row.email || '-' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="电话" width="140" align="center">
          <template #default="{ row }">
            <div class="phone-cell">
              <el-icon><Phone /></el-icon>
              <span>{{ row.phone || '-' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="roleId" label="角色" width="110" align="center">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.roleId)" size="small" effect="dark">
              {{ getRoleText(row.roleId) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="adoptionQuota" label="领养配额" width="110" align="center">
          <template #default="{ row }">
            <el-tag type="info" size="small" effect="plain">{{ row.adoptionQuota || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="90" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small" effect="dark">
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="180" align="center">
          <template #default="{ row }">
            <span class="time-text">{{ formatTime(row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" align="center" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button 
                size="small" 
                type="primary" 
                @click="editUser(row)"
                :icon="Edit"
              >
                编辑
              </el-button>
              <el-button 
                size="small" 
                type="success" 
                @click="resetPassword(row.id)"
                :icon="Lock"
              >
                重置密码
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="deleteUser(row.id)"
                :icon="Delete"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <el-empty 
        v-if="!loading && filteredList.length === 0" 
        description="暂无用户数据"
        style="margin: 40px 0;"
      />

      <!-- 分页 -->
      <div class="pagination-container" v-if="filteredList.length > 0">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑表单对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑用户' : '新增用户'" 
      width="600px"
      @close="handleDialogClose"
    >
      <el-form 
        ref="formRef"
        :model="form" 
        :rules="formRules" 
        label-width="100px"
        :key="dialogKey"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="form.username" 
            placeholder="请输入用户名"
            clearable
            :disabled="isEdit"
          />
        </el-form-item>
        
        <el-form-item label="昵称">
          <el-input 
            v-model="form.nickname" 
            placeholder="请输入昵称（选填）"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="form.email" 
            placeholder="请输入邮箱（选填）"
            clearable
          >
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="电话" prop="phone">
          <el-input 
            v-model="form.phone" 
            placeholder="请输入电话号码（选填）"
            clearable
          >
            <template #prefix>
              <el-icon><Phone /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input 
            v-model="form.password" 
            type="password"
            placeholder="请输入密码（必填）"
            show-password
            clearable
          />
        </el-form-item>
        
        <el-form-item label="角色">
          <el-select v-model="form.roleId" placeholder="选择角色" style="width: 100%;">
            <el-option label="普通用户" :value="1" />
            <el-option label="志愿者" :value="2" />
            <el-option label="管理员" :value="3" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="领养配额">
          <el-input-number 
            v-model="form.adoptionQuota" 
            :min="0"
            :max="100"
            placeholder="请输入领养配额"
            style="width: 100%;"
          />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-switch 
            v-model="form.status" 
            :active-value="1"
            :inactive-value="0"
            active-text="正常"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser" :loading="saving">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Plus, Search, Refresh, Edit, Delete, Message, Phone, Lock } from '@element-plus/icons-vue'
import axios from 'axios'

const users = ref([])
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const searchKeyword = ref('')
const filterRole = ref('')
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogKey = ref(0)

const form = ref({
  id: null,
  username: '',
  nickname: '',
  email: '',
  phone: '',
  password: '',
  roleId: 1,
  adoptionQuota: 0,
  status: 1
})

// 动态表单验证规则
const formRules = computed(() => {
  const rules = {
    username: [],
    email: [],
    phone: [],
    password: []
  }
  
  // 只有添加用户时才要求用户名和密码必填
  if (!isEdit.value) {
    rules.username = [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' }
    ]
    rules.password = [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, message: '密码长度至少6个字符', trigger: 'blur' }
    ]
  } else {
    // 编辑时：用户名如果填写则验证长度
    rules.username = [
      { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' }
    ]
    // 编辑时：如果填写了密码，则验证长度
    rules.password = [
      { min: 6, message: '密码长度至少6个字符', trigger: 'blur' }
    ]
  }
  
  // 邮箱格式验证（如果填写了邮箱）
  rules.email = [
    { 
      validator: (rule, value, callback) => {
        if (value && value.trim() !== '') {
          const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
          if (!emailRegex.test(value)) {
            callback(new Error('请输入正确的邮箱格式'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
  
  // 电话格式验证（如果填写了电话）
  rules.phone = [
    { 
      validator: (rule, value, callback) => {
        if (value && value.trim() !== '') {
          const phoneRegex = /^1[3-9]\d{9}$/
          if (!phoneRegex.test(value)) {
            callback(new Error('请输入正确的手机号码'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
  
  return rules
})

// 筛选后的列表
const filteredList = computed(() => {
  let result = users.value
  
  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(user => 
      (user.username && user.username.toLowerCase().includes(keyword)) ||
      (user.nickname && user.nickname.toLowerCase().includes(keyword)) ||
      (user.email && user.email.toLowerCase().includes(keyword)) ||
      (user.phone && user.phone.includes(keyword))
    )
  }
  
  // 角色筛选
  if (filterRole.value !== '' && filterRole.value !== null) {
    result = result.filter(user => user.roleId === filterRole.value)
  }
  
  // 分页
  total.value = result.length
  const start = (page.value - 1) * pageSize.value
  const end = start + pageSize.value
  return result.slice(start, end)
})

const formatTime = (time) => {
  if (!time) return '-'
  if (typeof time === 'string' && time.includes('T')) {
    return time.replace('T', ' ').substring(0, 19)
  }
  return time
}

const getRoleText = (roleId) => {
  const roleMap = {
    1: '普通用户',
    2: '志愿者',
    3: '管理员'
  }
  return roleMap[roleId] || '未知'
}

const getRoleType = (roleId) => {
  const typeMap = {
    1: 'info',
    2: 'warning',
    3: 'danger'
  }
  return typeMap[roleId] || 'info'
}

const formatImageUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  return `http://localhost:8080${url.startsWith('/') ? url : '/' + url}`
}

async function getUsers() {
  loading.value = true
  try {
    const res = await axios.get('http://localhost:8080/api/admin/user/list')
    if (res.data.code === 200) {
      users.value = res.data.data || []
    } else {
      ElMessage.error(res.data.msg || '获取用户列表失败')
      users.value = []
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
    users.value = []
  } finally {
    loading.value = false
  }
}

function openAddDialog() {
  isEdit.value = false
  dialogKey.value++ // 更新 key 以重置表单验证
  form.value = {
    id: null,
    username: '',
    nickname: '',
    email: '',
    phone: '',
    password: '',
    roleId: 1,
    adoptionQuota: 0,
    status: 1
  }
  dialogVisible.value = true
}

function editUser(row) {
  console.log('编辑用户:', row)
  isEdit.value = true
  dialogKey.value++ // 更新 key 以重置表单验证
  
  // 确保表单数据完整
  form.value = {
    id: row.id,
    username: row.username || '',
    nickname: row.nickname || '',
    email: row.email || '',
    phone: row.phone || '',
    password: '', // 编辑时不显示密码
    roleId: row.roleId || 1,
    adoptionQuota: row.adoptionQuota || 0,
    status: row.status !== undefined ? row.status : 1
  }
  
  dialogVisible.value = true
  
  // 等待 DOM 更新后清除验证状态
  setTimeout(() => {
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  }, 100)
}

function handleDialogClose() {
  formRef.value?.resetFields()
  form.value = {}
  isEdit.value = false
}

async function saveUser() {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请完善表单信息')
      return
    }
    
    saving.value = true
    try {
      const submitData = { ...form.value }
      
      // 如果是编辑且密码为空，不传递密码字段
      if (isEdit.value && !submitData.password) {
        delete submitData.password
      }
      
      const url = isEdit.value 
        ? 'http://localhost:8080/api/admin/user/update' 
        : 'http://localhost:8080/api/admin/user/add'
      const method = isEdit.value ? 'put' : 'post'
      
      const res = await axios({ url, method, data: submitData })
      if (res.data.code === 200) {
        ElMessage.success(res.data.msg || (isEdit.value ? '更新成功' : '添加成功'))
        dialogVisible.value = false
        getUsers()
      } else {
        ElMessage.error(res.data.msg || '操作失败')
      }
    } catch (error) {
      console.error('保存用户失败:', error)
      ElMessage.error('操作失败：' + (error.response?.data?.msg || error.message || '未知错误'))
    } finally {
      saving.value = false
    }
  })
}

async function deleteUser(id) {
  try {
    await ElMessageBox.confirm('确定删除该用户吗？删除后无法恢复。', '提示', {
      type: 'warning',
      confirmButtonText: '确定删除',
      cancelButtonText: '取消'
    })
    
    const res = await axios.delete(`http://localhost:8080/api/admin/user/delete/${id}`)
    if (res.data.code === 200) {
      ElMessage.success('删除成功')
      // 如果当前页没有数据了，返回上一页
      if (filteredList.value.length === 1 && page.value > 1) {
        page.value--
      }
      getUsers()
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

async function changeQuota(row) {
  try {
    const { value } = await ElMessageBox.prompt('请输入新的领养配额', '修改配额', {
      inputValue: row.adoptionQuota || 0,
      inputValidator: (value) => {
        const num = Number(value)
        if (isNaN(num) || num < 0) {
          return '请输入有效的数字（>= 0）'
        }
        return true
      },
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    
    if (value !== null) {
      const res = await axios.put('http://localhost:8080/api/admin/user/quota', null, {
        params: { id: row.id, quota: value }
      })
      if (res.data.code === 200) {
        ElMessage.success('配额修改成功')
        getUsers()
      } else {
        ElMessage.error(res.data.msg || '配额修改失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('修改配额失败:', error)
      ElMessage.error('修改配额失败')
    }
  }
}

async function resetPassword(id) {
  try {
    await ElMessageBox.confirm('确定将该用户密码重置为默认值 123456 吗？', '警告', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    
    const res = await axios.put('http://localhost:8080/api/admin/user/resetPassword', null, {
      params: { id }
    })
    
    if (res.data.code === 200) {
      ElMessage.success(res.data.msg || '密码重置成功')
    } else {
      ElMessage.error(res.data.msg || '密码重置失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置密码失败:', error)
      ElMessage.error('重置密码失败：' + (error.response?.data?.msg || error.message || '未知错误'))
    }
  }
}

const handleSearch = () => {
  page.value = 1
}

const handleReset = () => {
  searchKeyword.value = ''
  filterRole.value = ''
  page.value = 1
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  page.value = 1
}

const handleCurrentChange = (newPage) => {
  page.value = newPage
}

onMounted(getUsers)
</script>

<style scoped>
.user-manage-page {
  width: 100%;
}

.main-card {
  min-height: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 22px;
  color: #409eff;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.id-text {
  font-family: 'Courier New', monospace;
  font-weight: 600;
  color: #909399;
}

.username-text {
  font-weight: 600;
  color: #303133;
}

.nickname-text {
  color: #606266;
}

.time-text {
  color: #909399;
  font-size: 13px;
}

.email-cell,
.phone-cell {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
}

.email-cell .el-icon,
.phone-cell .el-icon {
  color: #909399;
  font-size: 16px;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  font-size: 14px;
}

:deep(.el-table__header) {
  background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
}

:deep(.el-table__header th) {
  background: transparent !important;
  border-bottom: 2px solid #e4e7ed;
  padding: 18px 0;
  font-weight: 600;
  color: #303133;
  letter-spacing: 0.5px;
}

:deep(.el-table__body tr) {
  transition: all 0.2s ease;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f0f9ff !important;
}

:deep(.el-table__body td) {
  padding: 18px 0;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-table__row:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

/* 操作按钮组样式 */
.action-buttons {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
}

.action-buttons .el-button {
  margin: 0;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 表单样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
}
</style>